<?php

/**
 *  供应商商品管理
 */

namespace app\admin\controller;

use think\Lang;
use think\Db;
use think\Session;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Product extends AdminControl
{

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/product.lang.php');
    }

    /**
     * 商品管理
     */
    public function index()
    {
        $goods_model = model('goods');
        /**
         * 处理商品分类
         */
        $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;
        $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
        $this->assign('gc_json', json_encode($gccache_arr['showclass']));
        $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));

        /**
         * 查询条件
         */
        $where = array();
        $search_goods_name = trim(input('param.search_goods_name'));
        if ($search_goods_name != '') {
            $where['goods_name'] = array('like', '%' . $search_goods_name . '%');
        }

        // 审核时间查询
        $search_check_time = input('param.search_check_time');
        if ($search_check_time) {
            $where['check_time'] = array('like', '%' . $search_check_time . '%');
        }
        // 提交时间查询
        $search_add_time = input('param.search_add_time');
        if ($search_add_time) {
            $start_add_time = strtotime($search_add_time);
            $search_add_time_two = strtotime($search_add_time.' 23:59:59');

            $where['goods_addtime'] = array('between', [$start_add_time, $search_add_time_two]);
        }

        $search_store_name = trim(input('param.search_store_name'));
        if ($search_store_name != '') {
            $where['store_name'] = array('like', '%' . $search_store_name . '%');

        }
        $search_store_id = trim(input('param.search_store_id'));
        if ($search_store_id != '') {
            $where['store_id'] = $search_store_id;
        }
        $b_id = intval(input('param.b_id'));
        if ($b_id > 0) {
            $where['brand_id'] = $b_id;
        }
        if ($choose_gcid > 0) {
            $where['gc_id_' . ($gccache_arr['showclass'][$choose_gcid]['depth'])] = $choose_gcid;
        }
        $goods_state = input('param.goods_state');
        if (in_array($goods_state, array('0', '1', '10'))) {
            $where['goods_state'] = $goods_state;
        }

        $type = input('param.type');
        $search_commonid = intval(input('param.search_commonid'));
        if ($search_commonid > 0) {
            $where['goods_commonid'] = $search_commonid;
        }
        switch ($type) {
            // 违规下架
            case 'lockup':
                #筛选商品
                $where['goods_status'] = 2;
                $goods_list = $goods_model->getGoodsCommonLockUpLists($where);
                break;
            // 等待审核
            case 'waitverify':
                #筛选商品
                $where['goods_status'] = 0;
                $goods_list = $goods_model->getGoodsCommonWaitVerifyList($where, '*', 10, 'goods_commonid desc');break;
            case 'status_up':
                #筛选商品
                $where['goods_status'] = 4;
                //p($where);die;
                $goods_list = $goods_model->getGoodsCommonWaitVerifyLists($where, '*', 10, 'goods_verify desc, goods_commonid desc');
                break;
            // 全部商品
            default:
                #筛选商品
                $where['goods_status'] = array('in', '0,1,2,3');
                $goods_verify = input('param.goods_verify');
                if ($goods_verify != '') {
                    $where['goods_status'] = $goods_verify;
                }
                $goods_list = $goods_model->getGoodsCommonList($where, '*', 10, 'check_time desc, goods_commonid desc');
                break;
        }
         //获取分类名称
         $goods_lists = getClassName($goods_list);
        $this->assign('goods_list', $goods_lists);

        $this->assign('show_page', $goods_model->page_info->render());

        $storage_array = $goods_model->calculateStorage($goods_list);
        $this->assign('storage_array', $storage_array);

        // 品牌
        $brand_list = model('brand')->getBrandPassedList(array());

        $this->assign('search', $where);
        $this->assign('brand_list', $brand_list);

        $this->assign('state', array('1' => lang('goods_state_1'), '0' => lang('goods_state_0'), '10' => lang('goods_state_10'), '100' => '审核中'));
        $this->assign('verify', array('1' => '通过', '2' => '未通过', '3' => '审核通过，自己操作下架', '10' => '待审核','0' => '待审核',));
        $this->assign('ownShopIds', array_fill_keys(model('store')->getOwnShopIds(), true));

        $type = input('param.type');
        if (!in_array($type, array('lockup', 'waitverify', 'allgoods'))) {
            $type = 'allgoods';
        }

        $this->assign('type', $type);
        $this->setAdminCurItem($type);
        return $this->fetch();
    }


    /*
      审核商品
     */
    public function goods_setting_price()
    {
        if (request()->isPost()) {
            $data = input('post.');
            /* p($data);die;*/
            $goods_commonid = $data['commonids'];
            $goods_info = db('goods')->where('goods_commonid', $goods_commonid)->select();
            if (input('status','1') == 0) {
                #没有通过
                /*   $update1['freight'] = 0;*/
                $update1['score'] = 0;
                $update1['install_money'] = -1;
                $update1['t_type'] = 0;
                $update1['g_value'] = 0;
                $update1['g_type'] = 0;
                $update1['t_value'] = 0;

                $update1['technician_price'] = '';

                $update1['ti_final_price'] = 0;
                $update1['gu_final_price'] = 0;

                #更新goods清空
                foreach ($goods_info as $k => $v) {
                    db('goods')->where('goods_id', $v['goods_id'])->data($update1)->update();
                }
                $data = [
                    'goods_stateremark' => $data['content'],
                    'goods_status' => '2',
                    'check_time' => date('Y-m-d H:i:s', time()),
                    'check_by_id' => Session::get('admin_id'),
                    'check_by_name' => Session::get('admin_name'),
                ];
                db('goodscommon')->where('goods_commonid', $goods_commonid)->data($data)->update();
                dsLayerOpenSuccess('操作成功');
            } else {

                #通过
                #判断goods 是否都已经设置过加价
                $aaa = 0;
                foreach ($goods_info as $k => $v) {
                    /*p($v);die;*/
                    if ($v['t_type'] == 0) {
                        $aaa = 1;
                    }
                }
                if ($aaa == 0) {
                    $data = [
                        'goods_status' => 1,
                        'is_price' => 1,
                        'check_time' => date('Y-m-d H:i:s', time()),
                        'check_by_id' => Session::get('admin_id'),
                        'check_by_name' => Session::get('admin_name'),
                    ];
                    db('goodscommon')->where('goods_commonid', $goods_commonid)->data($data)->update();
                    $this->log($_SESSION['admin']['admin_name'].'操作审核商品id'.$goods_commonid, 1);
                    dsLayerOpenSuccess('操作成功');
                } else {
                    $this->error('其中含有未设置加价的规格');
                }
            }

        } else {
            $commonid = input('param.commonid');
            $is_edit = input('param.is_edit','0');

            $this->assign('is_edit', $is_edit);
            $goods_info = db('goods')->where(['goods_commonid' => $commonid])->select();
            foreach ($goods_info as $k => $v) {
                if ($v['t_type'] == 0) {
                    $goods_info[$k]['t_price'] = '未设置';
                    $goods_info[$k]['g_price'] = '未设置';
                } else {
                    if ($v['t_type'] == 1) {
                        $goods_info[$k]['t_price'] = $v['goods_price'] + ($v['goods_price'] * $v['t_value'] * 0.01);
                    } elseif ($v['t_type'] == 2) {
                        $goods_info[$k]['t_price'] = $v['goods_price']  + $v['t_value'];
                    }
                    if ($v['g_type'] == 1) {
                        $goods_info[$k]['g_price'] = $v['goods_price'] + $v['goods_price'] * $v['g_value'] * 0.01;
                    } elseif ($v['g_type'] == 2) {
                        $goods_info[$k]['g_price'] = $v['goods_price']  + $v['g_value'];
                    }
                }

            }

            $json_goods_info = json_encode($goods_info);
            $this->assign('goods_info', $goods_info);
            $this->assign('json_goods_info', $json_goods_info);
            $goods = model('Goods')->where(['goods_commonid' => $commonid])->find();
            $this->view->goods = $goods;
            $this->assign('commonids', $commonid);
            return $this->fetch();
        }
    }

    /*
      设置规格实际价格
     */
    public function set_price()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $goods_commonid = $data['commonids'];
            if (empty($data['commonids'])) {
                $this->error('操作错误');
            }
            //  $update1['technician_price'] = $data['technician_price'];
            $update1['score'] = $data['score'];
            if ($data['status'] == 1) {
                $update1['install_money'] = $data['install_money'];
            } else {
                $update1['install_money'] = 0;
            }

            $update1['t_type'] = $data['t_type'];
            $update1['g_value'] = $data['g_value'];
            $update1['g_type'] = $data['g_type'];
            $update1['t_value'] = $data['t_value'];
            if (!strpos($goods_commonid, ',')) {
                $goods_info = db('goods')->where('goods_id', $goods_commonid)->field('goods_price')->find();

                    if ($data['t_type'] == 1) {
                        $update1['ti_final_price'] = $goods_info['goods_price'] + ($goods_info['goods_price'] * $data['t_value'] * 0.01);
                    } elseif ($data['t_type'] == 2) {
                        $update1['ti_final_price'] = $goods_info['goods_price']  + $data['t_value'];
                    }

                    if ($data['g_type'] == 1) {
                        $update1['gu_final_price'] = $goods_info['goods_price'] + $goods_info['goods_price'] * $data['g_value'] * 0.01;
                    } elseif ($data['g_type'] == 2) {
                        $update1['gu_final_price'] = $goods_info['goods_price']  + $data['g_value'];
                    }

                $res = db('goods')->where('goods_id', $goods_commonid)->data($update1)->update();
            } else {
                $ids = explode(',', $goods_commonid);
                foreach ($ids as $k => $v) {
                    $goods_info = db('goods')->where('goods_id', $v)->field('goods_price')->find();
                 if ($data['t_type'] == 1) {
                        $update1['ti_final_price'] = $goods_info['goods_price'] + ($goods_info['goods_price'] * $data['t_value'] * 0.01);
                    } elseif ($data['t_type'] == 2) {
                        $update1['ti_final_price'] = $goods_info['goods_price']  + $data['t_value'];
                    }
                    if ($data['g_type'] == 1) {
                        $update1['gu_final_price'] = $goods_info['goods_price'] + $goods_info['goods_price'] * $data['g_value'] * 0.01;
                    } elseif ($data['g_type'] == 2) {
                        $update1['gu_final_price'] = $goods_info['goods_price']  + $data['g_value'];
                    }
                    $res = db('goods')->where('goods_id', $v)->data($update1)->update();
                }

            }

            $goods = db('goods')->where(['goods_id'=>$goods_commonid])->find();
            //修改购物车商品的状态为已关闭
            $cart_info = db('cart')->where(['goods_commonid'=>$goods['goods_commonid']])->select();
            if(!empty($cart_info)){
                foreach ($cart_info as $key => $value) {
                    db('cart')->where(['goods_commonid'=>$value['goods_commonid']])->update(['status'=>1]);
                }
            }

            if (!$res) {
                dsLayerOpenSuccess('设置价格失败');
            }
            dsLayerOpenSuccess('设置价格成功');
        } else {
            $commonid = input('param.commonid');

            $is = strstr($commonid, ',');
            if (empty($is)) {
                $goods_info = db('goods')->where(['goods_id' => $commonid])->find();
              //  p($goods_info);die;
                $this->assign('goods_info', $goods_info);
                $this->assign('commonids', $commonid);
                return $this->fetch();
            }
            $info = [
                'install_money'=> 0,
                't_type' => 1,
                't_value' => 0,
                'g_type' => 1,
                'g_value' => 0
            ];
            $this->assign('goods_info', $info);
            $this->assign('commonids', $commonid);
            return $this->fetch();
        }
    }


    /**
     * 主商品详情页
     */
    public function goods_setting_info()
    {
        if (request()->isPost()) {
        } else {
            $config = db('config')->where('code', 'qiniu_http')->find();
            $this->assign('http_name', $config['value']);
            $commonid = input('param.commonid');
            $goods = db('y_goods')->where(['goods_commonid' => $commonid])->find();
            $this->view->goods = $goods;
            $this->assign('commonids', $commonid);
            $goods = db('goods')->where(['goods_commonid' => $commonid])->select();
            foreach($goods as $k=>$v){
                if (empty($v['t_value'])) {
                    $goods[$k]['t_price'] = '未设置';
                    $goods[$k]['g_price'] = '未设置';
                } else {
                    if ($v['t_type'] == 1) {
                        $goods[$k]['t_price'] = $v['goods_price'] + ($v['goods_price'] * $v['t_value'] * 0.01);
                    } elseif ($v['t_type'] == 2) {
                        $goods[$k]['t_price'] = $v['goods_price']  + $v['t_value'];
                    }
                    if ($v['g_type'] == 1) {
                        $goods[$k]['g_price'] = $v['goods_price'] + $v['goods_price']  * $v['g_value'] * 0.01;
                    } elseif ($v['g_type'] == 2) {
                        $goods[$k]['g_price'] = $v['goods_price'] +  + $v['g_value'];
                    }
                }
            }


            $this->assign('goods', $goods);
            $goods_info = db('goodscommon')->where(['goods_commonid' => $commonid])->find();
            if (empty($goods_info['files'])) {
                $goods_info['files_info'] = '';
            } else {
                $goods_info['files_info'] = json_decode($goods_info['files'],true);
                $goods_info['files_info']['old_file_name'] = explode(',',$goods_info['files_info']['old_file_name']);
                $goods_info['files_info']['new_file_name'] = explode(',',$goods_info['files_info']['new_file_name']);
            }
            //p($goods_info);die;
            $this->assign('goods_info', $goods_info);

            $goods_img = db('goodsimages')->where(['goods_commonid' => $commonid])->select();
            $this->assign('goods_img', $goods_img);

            return $this->fetch('store_goods_detail');
        }
    }

    /**
     * 子商品详情页
     */
         public function goods_setting_infos()
    {
        if (request()->isPost()) {
        } else {
            $commonid = input('param.goods_id');
            $goods = db('goods')->where(['goods_id' => $commonid])->find();
            $goods_info = db('goodscommon')->where(['goods_commonid' => $goods['goods_commonid']])->find();
            if (empty($goods['files'])) {
                $goods['files_info'] = '';
            } else {
                $goods['files_info'] = json_decode($goods['files'], true);
                $goods['files_info']['old_file_name'] = explode(',', $goods['files_info']['old_file_name']);
                $goods['files_info']['new_file_name'] = explode(',', $goods['files_info']['new_file_name']);
            }
            if (empty($goods['t_value'])) {
                $goods['t_price'] = '未设置';
                $goods['g_price'] = '未设置';
            } else {
                if ($goods['t_type'] == 1) {
                    $goods['t_price'] = $goods['goods_price'] + ($goods['goods_price']  * $goods['t_value'] * 0.01);
                } elseif ($goods['t_type'] == 2) {
                    $goods['t_price'] = $goods['goods_price'] + $goods['t_value'];
                }
                if ($goods['g_type'] == 1) {
                    $goods['g_price'] = $goods['goods_price'] + $goods['goods_price'] * $goods['g_value'] * 0.01;
                } elseif ($goods['g_type'] == 2) {
                    $goods['g_price'] = $goods['goods_price']  + $goods['g_value'];
                }
            }
            #质保期限 1--0，2--三个月， 3--六个月，4--一年 5-- 两年 6 -- 三年
            $this->assign('warranty_period_text',array('0'=>'未设置','1'=>'不包含','2'=>'三个月','3'=>'六个月','4'=>'一年','5'=>'两年','6'=>'三年'));
            $this->assign('goods', $goods);
            $this->assign('goods_info', $goods_info);
            $config = db('config')->where('code', 'qiniu_http')->find();
            $this->assign('http_name', $config['value']);
            return $this->fetch( 'goods_setting_info');
        }
    }

    /*
      选择教程首页
     */
    public function goods_setting_course()
    {
       /* if (request()->isPost()) {
            $data = input('post.');
            $data['add_time'] = time();
            $arr = Db::name('course_goods')->where(['goods_id' => $_POST['goods_id']])->find();
            if (!empty($arr)) {
                Db::name('course_goods')->where(['id' => $arr['id']])->delete();
            }
            $res = Db::name('course_goods')->data($data)->insert();
            if (!$res) {
                $this->error('设置教程失败');
            }
            dsLayerOpenSuccess('设置教程成功');


        } else {*/

            $commonid = input('param.commonid');
            $goods_list = db('goods')->where(['goods_commonid' => $commonid])->select();
            if(empty($goods_list)){
                $this->error('操作失败');
            }

           /* $course = Db::name('course')->where(['cat_id' => $goods_list['0']['gc_id'], 'brand_id' => $goods_list['0']['brand_id']])->select();
            if (empty($course)) {
                echo "商品对应的分类或品牌下没有教程";
                die;
            }*/
            $this->assign('goods_info',$goods_list);
            $this->assign('commonids', $commonid);
            return $this->fetch();
        /*}*/
    }


    /*
      选择教程
     */
    public function setting_course()
    {
        if (request()->isPost()) {
            $course_id = input('post.course_id','');
              if(empty($course_id)){
                $this->error('操作失败');
            }

           $course_info = db('course')->where('id',$course_id)->find();
           if(empty($course_info)){
                $this->error('操作失败');
            }

            $goods_id = input('post.goods_id','');
             if(empty($goods_id)){
                $this->error('操作失败');
            }

            if(!strpos($goods_id,',')){
               $res = db('goods')->where(['goods_id' => $goods_id])->data(['course_id'=>$course_id,'course_name'=>$course_info['title']])->update();
            }else{
                $goods_array = explode(',',$goods_id);
              foreach($goods_array as $k=>$v){
                $res = db('goods')->where(['goods_id' => $v])->data(['course_id'=>$course_id,'course_name'=>$course_info['title']])->update();
              }
            }
            
            dsLayerOpenSuccess('设置教程成功');

        } else {

            $goods_id = input('param.goods_id');
            if(empty($goods_id)){
                $this->error('操作失败');
            }
            if(!strpos($goods_id,',')){
               $goods_list = db('goods')->where(['goods_id' => $goods_id])->find();
               if(empty($goods_list)){
                $this->error('操作失败');
               }
            }else{
                $goods_array = explode(',',$goods_id);
            $goods_list = db('goods')->where(['goods_id' => $goods_array['0']])->find();
               if(empty($goods_list)){
                $this->error('操作失败');
               }
            }
            $course = db('course')->where(['cat_id' => $goods_list['gc_id'], 'brand_id' => $goods_list['brand_id']])->field('id,title')->where('status','0')->where('type','in','1,2')->order('add_time','desc')->select();
            if (empty($course)) {
                echo "商品对应的分类或品牌下没有教程";die;
            }
            $this->assign('course',$course);
            $this->assign('goods_id', $goods_id);
            return $this->fetch();
        }
    }


    //ajax获取同一个commonid下面的商品信息
    public function get_goods_list_ajax()
    {
        $common_id = input('param.commonid');
        if (empty($common_id)) {
            $this->error(lang('param_error'));
        }
        $map['goods_commonid'] = $common_id;
        $goods_model = model('goods');
        $common_info = $goods_model->getGoodeCommonInfo($map, 'spec_name');
        $goods_list = $goods_model->getGoodsList($map);
        //halt($goods_list);
        $spec_name = array_values((array)unserialize($common_info['spec_name']));
        foreach ($goods_list as $key => $val) {
            $goods_spec = array_values((array)unserialize($val['goods_spec']));
            $spec_array = array();
            foreach ($goods_spec as $k => $v) {
                $spec_array[] = '<div class="goods_spec">' . $spec_name[$k] . ':' . '<em title="' . $v . '">' . $v . '</em>' . '</div>';
            }
            $goods_list[$key]['goods_image'] = goods_cthumb($val['goods_image']);
            $goods_list[$key]['goods_spec'] = implode('', $spec_array);
            $goods_list[$key]['url'] = url('Home/Goods/index', array('goods_id' => $val['goods_id']));
        }
        return json_encode($goods_list);
    }

    /**
     * ajax操作
     */
    public function ajax()
    {
        $goods_model = model('goods');
        switch (input('param.branch')) {
            case 'mall_goods_commend':
            case 'mall_goods_sort':
                if (empty($result)) {
                    $goods_model->editGoodsCommonById(array(trim(input('param.branch')) => trim(input('param.value'))), array(intval(input('param.id'))));
                    echo 'true';
                    exit;
                } else {
                    echo 'false';
                    exit;
                }
                break;
        }
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'allgoods',
                'text' => lang('goods_index_all_goods'),
                'url' => url('Product/index')
            ),
            array(
                'name' => 'lockup',
                'text' => '审核未通过商品',
                'url' => url('Product/index', ['type' => 'lockup'])
            ),
            array(
                'name' => 'waitverify',
                'text' => lang('goods_index_waitverify_goods'),
                'url' => url('Product/index', ['type' => 'waitverify'])
            ),
        );
        return $menu_array;
    }

}

?>
